const TYPES = {
  NORMAL: 1,
  MARKED: 2,
};
const map = new Map(Object.entries(o));
const currentBook = new Map(Object.entries(o));
[...map.keys()]
  .filter((e) => e.toString().includes('tab'))
  .forEach((s) => {
    currentBook.delete(s);
  });
let arr = [...Array(currentBook.size).keys()].sort(() => 0.5 - Math.random());

new Vue({
  el: '#app',
  data: function () {
    return {
      arrLen: [...Array(currentBook.size).keys()].length,
      arr: arr,
      visible: false,
      ans: false,
      currentRemoved: {
        book: '',
        keys: [],
      },
      kana: false,
      exe: false,
      c: false,
      reverse: false,
      tagedSelectors: [],
      markeds: {
        keys: [],
        values: [],
      },
      checkList: [],
      current: 1,
      vocas: new Map(Object.entries(o)),
      currentBook: new Map(Object.entries(o)),
      currentEntity: 'jp',
      map: [],
      show3: false,
      title: 'Japanese A1',
    };
  },
  mounted() {
    this.switchBook(this.currentEntity);
    this.hint();
    this.loading();
    this.bindEvenet();
    this.loadMarkedlist();
    this.loadCheckedlist();
  },
  methods: {
    switchBook(name) {
      if (this.currentEntity !== name) {
        this.currentRemoved.keys = [];
      }
      this.currentEntity = name;
      switch (name) {
        case 'jp':
          this.loadBook(o, 'Japanese A1');
          break;
        case 'de':
          this.loadBook(de, 'Deutsch A2');
          break;
        default:
          this.loadBook(o);
          break;
      }
      if (this.exe) {
        this.queue();
      }
    },
    loadBook(book, name) {
      this.title = name == undefined ? this.title : name;
      this.vocas = new Map(Object.entries(book));
      const currentBook = new Map(Object.entries(book));
      [...currentBook.keys()]
        .filter((e) => e.toString().includes('~tab'))
        .forEach((s) => {
          currentBook.delete(s);
        });
      this.currentBook = currentBook;
      this.arr = [...Array(this.currentBook.size).keys()]
        .sort(() => 0.5 - Math.random())
        .filter((e) => !this.currentRemoved.keys.includes(e));
      this.arrLen = this.arr.length;
    },
    bindEvenet() {
      window.addEventListener('keyup', this.handleKeyup);
    },
    loadMarkedlist() {
      let list = localStorage.getItem('list');
      if (list != undefined) {
        this.markeds = JSON.parse(list);
      }
    },
    loadCheckedlist() {
      let checklist = localStorage.getItem('checklist');
      if (checklist != undefined) {
        this.checkList = JSON.parse(checklist);
      }
    },
    loading() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.78)',
      });
      setTimeout(() => {
        loading.close();
      }, 700);
    },
    removePart(key) {
      let taged = new Set(this.tagedSelectors);
      let tagedLen = taged.size;
      taged.forEach((e) => {
        if (e === key) {
          taged.delete(key);
        }
      });
      if (tagedLen == taged.size) {
        taged.add(key);
      }
      this.tagedSelectors = [...taged];
      let mm = [...this.vocas.keys()];
      let tabs = mm.filter((e) => e.includes('~tab'));
      let removeKeys = [];
      if (tabs.indexOf(key) == tabs.length - 1) {
        removeKeys = [...Array(this.vocas.size).keys()]
          .filter((e) => e > mm.indexOf(key))
          .map((e) => e - (tabs.indexOf(key) + 1));
      } else {
        removeKeys = [...Array(this.vocas.size).keys()]
          .filter(
            (e) =>
              e > mm.indexOf(key) && e < mm.indexOf(tabs[tabs.indexOf(key) + 1])
          )
          .map((e) => e - (tabs.indexOf(key) + 1));
        // 因为tab会占位置
      }

      let keylist = new Set(this.currentRemoved.keys);

      let len = keylist.size;
      keylist.forEach((e) => {
        if (removeKeys.includes(e)) {
          keylist.delete(e);
        }
      });
      if (len == keylist.size) {
        removeKeys.forEach((e) => keylist.add(e));
      }
      this.currentRemoved.keys = Array.from(keylist);
      this.loading();

      this.switchBook(this.currentEntity);
      const h = this.$createElement;
      this.$notify({
        title: `Successfully removed`,
        message: h(
          'i',
          { style: 'color: teal' },
          `This part of the exercise has been removed`
        ),
      });
    },
    hint() {
      this.$alert(
        `<code>Short Keys:</code> <br>
			<strong>[Space]:</strong> Start / Next <br>
			  <strong>[Enter]:</strong> See Answer <br>
			  <strong>[N]:</strong> Normal Exercise <br>
			  <strong>[M]:</strong> Marked Review <br>`,
        'HINT',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: 'OK',
        }
      );
    },
    queReverse() {
      this.map = this.map.reverse();
      console.log(this.map);
    },

    queue(type) {
      if (this.arr <= 0) {
        this.$message({
          message: 'no words!',
          type: 'danger',
        });
        return;
      }
      let q = '';
      this.exe = true;
      this.kana = false;
      this.visible = true;
      this.ans = false;
      let current = this.current;
      current = type != undefined ? type : this.current;
      this.current = current;

      if (current == TYPES.MARKED) {
        this.marked = true;
        this.title = 'Marked lists';
        let marr = [...this.markeds.keys.keys()].sort(
          () => 0.5 - Math.random()
        );
        let index = marr.shift();

        this.reverse
          ? (this.map = [
              this.markeds['values'][index],
              this.markeds['keys'][index],
            ])
          : (this.map = [
              this.markeds['keys'][index],
              this.markeds['values'][index],
            ]);
      } else if (current == TYPES.NORMAL) {
        this.marked = false;
        console.log('normal');
        if (this.arr.length >= 1) {
          q = Array.from(this.currentBook.entries())[this.arr.shift()];
          this.$message({
            message: `${this.arrLen - this.arr.length}/${this.arrLen}`,
            type: 'info',
          });
        } else {
          this.$message({
            message: 'Round finished!',
            type: 'success',
          });
          this.arr = [...Array(this.currentBook.size).keys()].sort(
            () => 0.5 - Math.random()
          );
          q = Array.from(this.currentBook.entries())[this.arr.shift()];
          let checklist = localStorage.getItem('checklist');
          let _date = new Date().toJSON().split('T')[0];
          if (checklist != undefined) {
            checklist = new Set(JSON.parse(checklist));
            checklist.add(_date);
          } else {
            checklist = new Set([_date]);
          }
          localStorage.setItem(
            'checklist',
            JSON.stringify(Array.from(checklist))
          );
          this.checkList = checklist;
          const h = this.$createElement;
          this.$notify({
            title: `Successfully checked in!`,
            message: h(
              'i',
              { style: 'color: teal' },
              `Today's plan has been completed!`
            ),
          });
        }
        this.reverse ? (this.map = q.reverse()) : (this.map = q);
      }
    },
    hover(item) {},
    handler(e) {
      this.queue();
    },
    answer(e) {
      this.ans = !this.ans;
    },
    goKana() {
      this.visible = true;
      this.exe = false;
      this.kana = true;
      this.switchBook('jp');
      this.title = 'kanatohaku';
    },
    handleKeyup(e) {
      if (e.code == 'Space') {
        this.handler();
      } else if (e.code == 'Enter') {
        this.answer();
      } else if (e.code == 'KeyM') {
        this.showMarked();
      } else if (e.code == 'KeyN') {
        this.showNormal();
      }
    },
    restrucArray(list) {
      return {
        keys: [...list.keys],
        values: [...list.values],
      };
    },
    pushO(list, item) {
      list = {
        keys: new Set(list.keys),
        values: new Set(list.values),
      };
      list.keys.add(item[0]);
      list.values.add(item[1]);
      return this.restrucArray(list);
    },
    showMarked() {
      let list = localStorage.getItem('list');
      if (list != undefined) {
        this.markeds = JSON.parse(list);
      }
      this.current = TYPES.MARKED;
      this.queue(TYPES.MARKED);
    },
    showNormal() {
      this.current = TYPES.NORMAL;
      this.queue(TYPES.NORMAL);
    },
    remove(item) {
      let list = this.markeds;
      list = {
        keys: new Set(list.keys),
        values: new Set(list.values),
      };
      list.keys.delete(item[0]);
      list.keys.delete(item[1]);
      list.values.delete(item[0]);
      list.values.delete(item[1]);
      this.markeds = this.restrucArray(list);
      if (list.keys.size == 0) {
        let checklist = localStorage.getItem('checklist');
        let _date = new Date().toJSON().split('T')[0];
        if (checklist != undefined) {
          checklist = new Set(JSON.parse(checklist));
          checklist.add(_date);
        } else {
          checklist = new Set([_date]);
        }
        localStorage.setItem(
          'checklist',
          JSON.stringify(Array.from(checklist))
        );
        this.checkList = checklist;
        const h = this.$createElement;
        this.$notify({
          title: `Successfully checked in!`,
          message: h(
            'i',
            { style: 'color: teal' },
            `Today's plan has been completed!`
          ),
        });
      }
      localStorage.setItem('list', JSON.stringify(this.restrucArray(list)));
    },
    sound(item) {
      if (this.currentEntity === 'jp') {
        let audio = new Audio(`./static/mp3/${item[1]}.mp3`);
        audio.play();
      }
    },
    mark(item) {
      this.save(item);
      this.answer();
    },
    removeAndQueue(item) {
      this.remove(item);
      this.queue();
    },
    save(item) {
      this.sound(item);
      this.$message({
        message: 'Saved!',
        type: 'success',
      });
      console.log('item', item);
      let l = localStorage.getItem('list');
      if (l == undefined) {
        let _list = {
          keys: [],
          values: [],
        };
        localStorage.setItem('list', JSON.stringify(this.pushO(_list, item)));
      } else {
        let _list = JSON.parse(localStorage.getItem('list'));
        localStorage.setItem('list', JSON.stringify(this.pushO(_list, item)));
      }
    },
  },
});
// const app = Vue.createApp(App);
// app.use(ElementPlus);
// app.mount('#app');
